package com.shadow.demo.shiro.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shadow.demo.common.bo.R;
import com.shadow.demo.data.BaseController;
import com.shadow.demo.data.shiro.entity.Role;
import com.shadow.demo.shiro.service.RolePermissionService;
import com.shadow.demo.shiro.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {

    private final RoleService roleService;
    private final RolePermissionService rolePermissionService;

    RoleController(
            RoleService roleService,
            RolePermissionService rolePermissionService
    ) {
        this.roleService = roleService;
        this.rolePermissionService = rolePermissionService;
    }

    @PostMapping("/list")
    public R getUserList(@RequestParam Map<String, Object> params) {
        Page<Role> page = roleService.getList(params);
        return successPage(page);
    }

    @GetMapping("detail/{id}")
    public R detail(@PathVariable String id) {
        return R.success(roleService.getById(id));
    }

    @PostMapping("save")
    public R save(@RequestBody Role role) {
        String msg = saveVerify(role);
        if (msg != null) {
            return R.fail(msg);
        }
        if (roleService.verifyExist(role.getCode())) {
            return R.fail("角色已经存在");
        }
        roleService.save(role);
        return R.success();
    }

    @PostMapping("update")
    public R update(@RequestBody Role role) {
        String msg = saveVerify(role);
        if (msg != null) {
            return R.fail(msg);
        }
        if (!roleService.verifyEditable(role.getId())) {
            return R.fail("账号不可被编辑");
        }
        roleService.saveOrUpdate(role);
        return R.success();
    }

    @PostMapping("config/permission/{id}")
    public R configRole(
            @PathVariable("id") String id,
            @RequestBody List<String> permissionList
    ) {
        Role role = roleService.getById(id);
        if (Objects.isNull(role)) {
            return R.fail("找不到角色");
        }
        rolePermissionService.configRole(role.getId(), permissionList);
        return R.success();
    }

    @PostMapping("/del/{ids}")
    public R del(@PathVariable("ids") String ids) {
        int change = roleService.delete(ids);
        return R.success(change);
    }

    /**
     * 保存验证
     *
     * @return 通过 null
     * 不通过 msg
     */
    private String saveVerify(final Role role) {
        if (StringUtils.isBlank(role.getName())) {
            return "角色名称不能为空";
        }
        if (StringUtils.isBlank(role.getCode())) {
            return "角色码不能为空";
        }
        return null;
    }
}
